const fs = require("fs");
const image = require("imageinfo"); // 引用imageinfo模块
function readFileList(path, filesList) {
    const files = fs.readdirSync(path);
    files.forEach((itm, index) => {
        const stat = fs.statSync(path + itm);
        if (stat.isDirectory()) {
            // 递归读取文件
            readFileList(path + itm + "/", filesList);
        } else {
            const obj = {}; // 定义一个对象存放文件的路径和名字
            obj.path = path; // 路径
            obj.filename = itm; // 名字
            filesList.push(obj);
        }
    });
}
const getFiles = {
    // 获取文件夹下的所有文件
    getFileList: function(path) {
        const filesList = [];
        readFileList(path, filesList);
        return filesList;
    },
    // 获取文件夹下的所有图片
    getImageFiles: function(path) {
        const imageList = [];
        this.getFileList(path).forEach(item => {
            const ms = image(fs.readFileSync(item.path + item.filename));
            ms.mimeType &&
                imageList.push("http://api.doodooke.com/icon/" + item.filename);
        });
        return imageList;
    },
    pagination(pageNo, pageSize, array) {
        const offset = (pageNo - 1) * pageSize;
        return offset + pageSize >= array.length
            ? array.slice(offset, array.length)
            : array.slice(offset, offset + pageSize);
    }
};
module.exports = class extends doodoo.Controller {
    /**
     *
     * @api {get} /icon/images/index 获取授权域名列表
     * @apiDescription
     * @apiGroup icon images
     * @apiVersion 0.0.1
     *
     * @apiParam {Number} page   页面id
     *
     * @apiSampleRequest /icon/images/index
     *
     */
    async index() {
        const { page = 1 } = this.query;
        const pageSize = 72;

        const srclist = getFiles.getImageFiles("www/icon/");
        const data = getFiles.pagination(page, pageSize, srclist);

        this.success({
            data: data,
            pagination: {
                page: Number(page),
                pageCount: Math.ceil(srclist.length / pageSize),
                pageSize: pageSize,
                rowCount: srclist.length
            }
        });
    }
};
